import RNFS from 'react-native-fs';

import { InitDownloadVideos, InitDownloadVideo } from './types';
import DownloadVideo from './downloadVideo';
import { VIDEO_TYPE_DESC, DOWNLOAD_PATH } from './constant';

let downloadVideoObject: DownloadVideo | null;

export const getCurrentDownloadVideoObject = (): DownloadVideo | null => {
  return downloadVideoObject;
};

export const initDownloadVideos = (props: InitDownloadVideos): void => {
  const {
    downloadVideos,
    onSuccess,
    onProgress,
    onDelete,
    onStart,
    onPause,
    onFail,
    init,
    getStore,
    isPrior
  } = props;

  // 存缓存
  downloadVideos.forEach((item): void => {
    const { parentId, parentTitle, id, title, type, url, size, source } = item;
    const store = getStore(id);

    // 如果是需要立刻下载的话不过滤已有下载项，直接覆盖
    if ((!store && !isPrior) || isPrior) {
      const [serverDir] = url.split(`/${VIDEO_TYPE_DESC[type]}`);
      const dirArray = serverDir.split('/');
      const folderName = `${parentId}/${dirArray[dirArray.length - 1]}`;

      init({
        id,
        title,
        type,
        url,
        size,
        serverDir,
        folderName,
        tsList: [],
        keyUrl: '',
        progress: 0,
        indexHasDone: false,
        keyHasDone: false,
        m3u8Path: '',
        parentId,
        parentTitle,
        isPaused: false,
        isFailed: false,
        startTime: '',
        continueTime: new Date(),
        duration: 0,
        source
      });
    }
  });

  // 如果是需要立刻下载的话，由于下载视频数组反转了，因此取最后一位开始下载
  const downloadStore = getStore(
    downloadVideos[isPrior ? downloadVideos.length - 1 : 0].id
  );

  if (!downloadVideoObject && downloadStore) {
    // 取最近的下载任务
    downloadVideoObject = new DownloadVideo({
      ...downloadStore,
      onSuccess,
      onProgress,
      onDelete,
      onStart,
      onPause,
      onFail
    });

    downloadVideoObject.start();
  }
};

export const initDownloadVideo = (props: InitDownloadVideo): void => {
  const {
    parentId,
    parentTitle,
    id,
    title,
    type,
    url,
    size,
    source,
    onSuccess,
    onProgress,
    onDelete,
    onStart,
    onPause,
    onFail,
    getStore,
    init
  } = props;

  const store = getStore(id);

  if (!store) {
    const [serverDir] = url.split(`/${VIDEO_TYPE_DESC[type]}`);
    const dirArray = serverDir.split('/');
    const folderName = `${parentId}/${dirArray[dirArray.length - 1]}`;

    init({
      id,
      title,
      type,
      url,
      size,
      serverDir,
      folderName,
      tsList: [],
      keyUrl: '',
      progress: 0,
      indexHasDone: false,
      keyHasDone: false,
      m3u8Path: '',
      parentId,
      parentTitle,
      isPaused: false,
      isFailed: false,
      startTime: '',
      continueTime: new Date(),
      duration: 0,
      source
    });
  }
  const downloadStore = getStore(id);

  if (!downloadVideoObject && downloadStore) {
    // 取最近的下载任务
    downloadVideoObject = new DownloadVideo({
      ...downloadStore,
      onSuccess,
      onProgress,
      onDelete,
      onStart,
      onPause,
      onFail
    });

    downloadVideoObject.start();
  }
};

export const removeDownloadVideoObject = (): void => {
  downloadVideoObject = null;
};

export const pauseDownloadVideoObject = (): void => {
  if (downloadVideoObject) {
    downloadVideoObject.pause();
  }
};

export const deleteDownloadVideoObject = (): void => {
  if (downloadVideoObject) {
    downloadVideoObject.delete();
  }
};

export const deleteOtherVideo = (folderName: string): void => {
  RNFS.unlink(`${DOWNLOAD_PATH}/${folderName}`);
};

export const deleteAllDownloadVideos = (): void => {
  RNFS.unlink(DOWNLOAD_PATH);
};
